/**
  ******************************************************************************
  * @file    socket-util.h
  * @author  Dragon.Chen
  * @version V1.1.0
  * @date    11-08-2013
  * @brief   socket通用函数接口
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT 2013 上海今中网络科技有限公司 </center></h2>
  ******************************************************************************
  */

#include "socket-util.h"

/**
  * @brief  设置描述符为阻塞状态
  * @param  arg1:fd
  * @retval	成功返回0, 失败返回-1
  */
int set_blocking(int fd)
{
	int val;

	if ( (val = fcntl(fd, F_GETFL, 0)) < 0)
		return -1;
	val &= ~O_NONBLOCK;
	if (fcntl(fd, F_SETFL, val) < 0)
		return -1;
	return 0;
}

/**
  * @brief  设置描述符为非阻塞状态
  * @param  arg1:fd
  * @retval	成功返回0, 失败返回-1
  */
int set_nonblocking(int fd)
{
	int val;

	if ( (val = fcntl(fd, F_GETFL, 0)) < 0)
		return -1;
	val |= O_NONBLOCK;
	if (fcntl(fd, F_SETFL, val) < 0)
		return -1;
	return 0;
}

/**
  * @brief  初始化服务器socket
  * @param  arg1 port
  * @retval 返回监听fd,失败程序exit
  */
int tcp_listen(int port, const char *ip)
{
    int serfd;
    int flag = 1;
    struct sockaddr_in sin;

    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(port);
    sin.sin_addr.s_addr = inet_addr(ip);

    assert_param( (serfd = socket(AF_INET, SOCK_STREAM, 0)) >= 0 );
#ifdef ENABLE_DEBUG
/******* sendbuf = 5120; mtu = 800 ******/
//   int recv_buf = 300;
//    setsockopt(serfd, SOL_SOCKET, SO_RCVBUF, &recv_buf, sizeof(int));
//    setsockopt(serfd, SOL_SOCKET, SO_SNDBUF, &recv_buf, sizeof(int));
#endif

    assert_param( setsockopt(serfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) == 0 );
    assert_param( bind(serfd, (struct sockaddr*)&sin, sizeof(sin)) == 0 );
    assert_param( listen(serfd, 65535) == 0 );

    return serfd;
}

/**
  * @brief  tcp连接
  * @param  arg1:ip地址   arg2:port
  * @retval 已连接套接字
  */
int tcp_connect(const char *ip, int port)
{
    int serfd;
    struct sockaddr_in sin;

    memset(&sin, 0, sizeof(sin));
    sin.sin_family = AF_INET;
    sin.sin_port = htons(port);
    sin.sin_addr.s_addr = inet_addr(ip);

    if ( (serfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        return -1;

    if ( connect(serfd, (struct sockaddr*)&sin, sizeof(sin)) <0)
        return -1;

    return serfd;
}

/******************* (C) COPYRIGHT 2013 上海今中网络科技有限公司 *****END OF FILE****/


















